/**
 * For the license, see main.cpp file
 */

#include "Qrm3Controller.h"
#include "MainGuiImpl.h"
#include "SettingsGlobalResource.h"
#include "P2PChat.h"

MainGuiImpl::MainGuiImpl()
{
	ui.setupUi(this);
	
	/* init icons */
	logoIconSmall = QIcon(":/qrm3wifi_logo_small_red");
	
	/* Centering the gui and show */
	dw = new QDesktopWidget();
	QRect geometry = dw->screenGeometry();
	setGeometry((geometry.width() / 2) - 265, (geometry.height() / 2) - 175, 530, 350);
	ui.tabWidget->setCurrentIndex(0);
	
	/* disable trayIcon checkbox if usupported */
	if(!QSystemTrayIcon::isSystemTrayAvailable())
		ui.trayIconCheckBox->setDisabled(true);

	/* Correct Font and EndLine */
#ifdef Q_OS_WIN32
	logFont = new QFont("Courier New", 9);
	endLine = QString("\r\n");
#else
	logFont = new QFont("Monospace", 9);  
	endLine = QString("\n");
#endif
	// set monospace font for log area
	ui.logTextEdit->setCurrentFont(*logFont);
	
	/* Set the font to the chat text area TODO: make the chat multicolor with HTML */
	ui.chatTextArea->setCurrentFont(*logFont);
	
	/* Set correct size for the chat spiltter */
	QList<int> sizes;
	sizes << 400 << 100;
	ui.chatSplitter->setSizes(sizes);
	
	
}

void MainGuiImpl::setConnections()
{
	/* Connects */
	connect(ui.restoreDefaultPushButton,	SIGNAL(clicked()), this, SLOT(restoreDefaultSettings()));
	connect(ui.storeSettingsPushButton,		SIGNAL(clicked()), this, SLOT(registerNewSettings()));
	connect(ui.loopAuthButton,				SIGNAL(clicked()), this, SLOT(startCronAuth()));
	connect(ui.singleAuthButton,			SIGNAL(clicked()), this, SLOT(startSingleAuth()));
	connect(ui.quitButton,					SIGNAL(clicked()), qApp, SLOT(quit()));
	connect(ui.aboutQtButton,				SIGNAL(clicked()), qApp, SLOT(aboutQt()));
	connect(ui.feedPushButton,				SIGNAL(clicked()), this, SLOT(loadRss()));	
	connect(ui.newsListWidget,				SIGNAL(itemDoubleClicked(QListWidgetItem *)),
											this, SLOT(openNews(QListWidgetItem *)));
	connect(ui.identityButton,				SIGNAL(clicked()), this, SLOT(showUserIdentetyGui()));
	connect(ui.disconnectConnectButton,		SIGNAL(clicked()), P2PChat::getInstance(), SLOT(startChat()));
	
	// other signal if we have a systray icon available
	if(isSystemTray)
		connect(	trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
					this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
}

void MainGuiImpl::hideEvent(QHideEvent *event)
{
		event->accept();
}

void MainGuiImpl::closeEvent(QCloseEvent *event)
{
	if(!isSystemTray)
	{
		int resp = 0;
		resp = QMessageBox::question(this,	"QRm3WiFi question",
											"Do you want to quit?",
											"Yes", "No", QString(), 0, 1);
		if(resp == 1)
		{
			event->ignore();
		}
		else
		{
			hide();
			event->accept();
		}
	}
	else  /* hide, ignore and show message on systray */
	{
		event->ignore();
		hide();
	}
}

void MainGuiImpl::startSingleAuth()
{
	/* if the cron authentication is active, skeep this event */
	if(Qrm3Controller::getInstance()->getCronTimer()->getTimer()->isActive())
		QMessageBox::warning(this, "QRm3WiFi warning",
									tr("The authenticator is already running.\n\n"
									"If you want a single shot authentication,\n"
									"please stop the cron authenticator!"),
									QMessageBox::Ok);
	else
		Qrm3Controller::getInstance()->getAuthenticator()->start();
}

void MainGuiImpl::startCronAuth()
{
	if(Qrm3Controller::getInstance()->getCronTimer()->getTimer()->isActive())	//STOP
	{
		ui.loopAuthButton->setText("Start authentication");
		Qrm3Controller::getInstance()->getTimeLine()->stop();	//for progress bar
		ui.CronProgressBar->setValue(0);
		Qrm3Controller::getInstance()->getCronTimer()->stopCron();
		if(isSystemTray)
			startStopAction->setText("Start authentication");
	}
	else		//START
	{
		ui.loopAuthButton->setText("Stop authentication");
		Qrm3Controller::getInstance()->getTimeLine()->setCurrentTime(0);
		Qrm3Controller::getInstance()->getTimeLine()->start();
		Qrm3Controller::getInstance()->getCronTimer()->startCron();
		if(isSystemTray)
			startStopAction->setText("Stop authentication");
		
		qDebug() <<		"Timeout cron:" 
				 <<		Qrm3Controller::getInstance()->getTimeLine()->duration() 
				 << 	"ms ["
				 <<		Qrm3Controller::getInstance()->getCronTimer()->getTimer()->interval() / 1000 / 60
				 <<		"Minute(s) ]";
	}	
}

void MainGuiImpl::restoreDefaultSettings()
{
	int resp = 0;
	
	resp = QMessageBox::question(this, "QRm3WiFi question",
										"Do you want restore the default settings?",
										"Yes", "No", QString(), 0, 1);
	if(resp != 1)
	{
		 Qrm3Controller::getInstance()->getSettingsExpert()->restoreDefaultSettings();
	}
}

void MainGuiImpl::registerNewSettings()
{
	int resp = 0;
	
	resp = QMessageBox::question(this, "QRm3WiFi question",
										"Do you want store the new settings?",
										"Yes", "No", QString(), 0, 1);
	
	if(resp != 1)
	{
		/* if the crontimer is changed */
		if(Qrm3Controller::getInstance()->getSettingsExpert()->getSetting(SETTING_CRON_TIME).toUInt() != 
				(unsigned int)ui.cronTimeSpinBox->value())
			Qrm3Controller::getInstance()->getCronTimer()->changeInterval((quint32)ui.cronTimeSpinBox->value());
		
		// Store all changed settings
		Qrm3Controller::getInstance()->getSettingsExpert()->registerQStringSetting(
						SETTING_USERNAME, ui.usernameLineEdit->text());

		Qrm3Controller::getInstance()->getSettingsExpert()->registerQByteArraySetting(
						SETTING_PASSWORD, ui.passwordLineEdit->text().toUtf8(), true);

		Qrm3Controller::getInstance()->getSettingsExpert()->registerQStringSetting(
						SETTING_SERVER_IP, ui.serverAddressLineEdit->text());

		Qrm3Controller::getInstance()->getSettingsExpert()->registerQuint32Setting(
						SETTING_SERVER_PORT, ui.serverPortSpinBox->value());

		Qrm3Controller::getInstance()->getSettingsExpert()->registerQuint32Setting(
						SETTING_CRON_TIME, ui.cronTimeSpinBox->value());
						
		Qrm3Controller::getInstance()->getSettingsExpert()->registerBoolSetting(
						SETTING_SYSTRAY, (ui.trayIconCheckBox->checkState() == Qt::Checked));
		
		//Store now!
		Qrm3Controller::getInstance()->getSettingsExpert()->forceSync();
	}
}

void MainGuiImpl::logLine(QString textToLog, bool showOnTray)
{
	if(textToLog != "")
	{
		ui.logTextEdit->setPlainText("[" + QDateTime::currentDateTime().toString("hh:mm") + "] " + 
									textToLog + endLine + ui.logTextEdit->toPlainText());		
	}
	else
	{
		ui.logTextEdit->setPlainText(textToLog + endLine + ui.logTextEdit->toPlainText());
	}
	
	if(showOnTray && isSystemTray)
	{
		trayIcon->showMessage(	"QRm3WiFi Information.",
								textToLog, 
								QSystemTrayIcon::Information,
								2 * 1000);
	}
}

void MainGuiImpl::changeTrayIcon(bool connected)
{
	if(isSystemTray)
	{
		if(connected)
		{
			trayIcon->setIcon(QIcon(":/qrm3wifi_logo_small_green"));
		}
		else
		{
			trayIcon->setIcon(QIcon(":/qrm3wifi_logo_small_red"));
		}
	}
}

void MainGuiImpl::createActions()
{
	startStopAction = new QAction("Start authentication", this);
	connect( startStopAction, SIGNAL(triggered()), this, SLOT(startCronAuth()));
	
	minimizeAction = new QAction(tr("Mi&nimize"), this);
	connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
	
	restoreAction = new QAction(tr("&Restore"), this);
	connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
	
	quitAction = new QAction(tr("&Quit"), this);
	connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}

void MainGuiImpl::createTrayIcon()
{
	trayIconMenu = new QMenu(this);
	trayIconMenu->addAction(startStopAction);
	trayIconMenu->addSeparator();
	trayIconMenu->addAction(minimizeAction);
	trayIconMenu->addAction(restoreAction);
	trayIconMenu->addSeparator();
	trayIconMenu->addAction(quitAction);
	
	trayIcon = new QSystemTrayIcon(this);
	trayIcon->setContextMenu(trayIconMenu);
	trayIcon->setIcon(logoIconSmall);
	trayIcon->show();
}

void MainGuiImpl::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
	switch(reason)
	{
		case QSystemTrayIcon::DoubleClick:
			if(isVisible() && isMinimized())
			{
				showNormal();
			}
			else if(isVisible() && !isMinimized())
			{
				hide();
			}
			else
			{
				show();
				showNormal();
			}
				
				
			break;
		default:
			;
	}

}

void MainGuiImpl::loadRss()
{
	if(ui.rssComboBox->currentIndex() != -1)
	{
		ui.rssInfoLabel->setText("<em>wait...</em>");
		ui.rssInfoLabel->setToolTip("");
		
		// start parser thread for the selected feed
		Qrm3Controller::getInstance()->getNewsParser()->setCurrentUrlAndStart
		(
			ui.rssComboBox->itemData(ui.rssComboBox->currentIndex()).toString()
		);
		qDebug() << "Selected feed:" << ui.rssComboBox->itemData(ui.rssComboBox->currentIndex()).toString();
	}
}

void MainGuiImpl::fillRSSList(QList<QString> rssKeys)
{
	QListIterator<QString> it = QListIterator<QString>(rssKeys);
	while(it.hasNext())
	{
		QString app = it.next();
		ui.rssComboBox->addItem(app, app);
	}
		
}

void MainGuiImpl::renderNewsError(QString error)
{
	qDebug() << error;
	ui.rssInfoLabel->setText("<b><font color='red'>Error:</font></b> " + error);
}

void MainGuiImpl::renderNews(FeedRSS *news)
{
	qDebug() << "news arrived at GUI...rendering.";
	ui.rssInfoLabel->setText("<a href=\"" + 
							*(news->getFeedLink()) + 
							"\">" +
							*(news->getFeedTitle()) + "</a>");

	ui.rssInfoLabel->setToolTip(*(news->getFeedDescription()));
	
	//remove all olds entries
	ui.newsListWidget->clear();
	
	//fill the list view
	for (int it = 0; it < news->getItems()->size(); it++) 
	{
		//stuff
		QListWidgetItem *item = new QListWidgetItem(news->getItems()->at(it).first);
		item->setData(Qt::ToolTipRole, news->getItems()->at(it).second);		//The entry url (showed also as tool tip)
		
		//add the news (rendering)
		ui.newsListWidget->addItem(item);
	}
	
}

void MainGuiImpl::openNews(QListWidgetItem *item)
{
	qDebug() << "Opening" << item->data(Qt::ToolTipRole).toString();
	if(QDesktopServices::openUrl(QUrl(item->data(Qt::ToolTipRole).toString())))
	{
		item->setBackgroundColor(QColor(Qt::green));	
	}
	else
		qWarning() << "Open url failed." << item->data(Qt::ToolTipRole).toString();
}

/**
 * SLOT: Show the user identity form
 */
void MainGuiImpl::showUserIdentetyGui()
{
	Qrm3Controller::getInstance()->showGuiUserIdentity();
}
